<script>
import { defineComponent, reactive, ref } from 'vue'
import MakeForm, { MakeFormState } from '@Components/makeForm'
import DataTable from '@Components/dataTable'
import {
  authRoleList,
  authRoleAdd,
  authRoleDel,
  authUserRoleList,
  authUserRoleDel,
  authUserRoleAdd,
} from '@Config/server/api'
import { message } from 'ant-design-vue'
import { createPagination, Messages, confirm } from '@Config/config'
import { useRoute, useRouter } from 'vue-router'
import { useUrl, transform_pre_fn } from '@Hooks/url'
import { useWin } from '@Hooks/win'
import BindUser from '@Page/role/components/bindUser'
import { cloneDeep, findIndex } from 'lodash'
import { maxSearchValue } from '@Untils'
export default defineComponent({
  components: {
    DataTable,
    MakeForm,
    BindUser,
  },
  setup(props, context) {
    let tableData = reactive({
      data: {
        source: [],
        columns: [
          {
            key: 'nickname',
            dataIndex: 'nickname',
            title: '昵称',
            width: '25%',
          },
          {
            key: 'roleName',
            dataIndex: 'roleName',
            title: '角色描述',
            width: '25%',
          },
          {
            key: 'username',
            dataIndex: 'username',
            title: '登录账号',
            width: '25%',
          },
          {
            key: 'operation',
            dataIndex: 'operation',
            title: '操作',
            width: '25%',
          },
        ],
      },
    })

    let custom = [
      {
        key: 'username',
        bodyFn: (text, record, index) => {
          return (
            <a-space direction="vertical">
              <span>{record.username}</span>
              {record.isSub == 1 && (
                <span>
                  <a-tag color="red">子账号</a-tag>
                </span>
              )}
            </a-space>
          )
        },
      },
      {
        key: 'operation',
        bodyFn: (text, record, index) => {
          return (
            <a-space>
              <a-popconfirm
                title="确定此项操作吗？"
                onConfirm={async () => {
                  record.local_loading = true
                  let _result = await authUserRoleDel({ ids: [record.id] })
                  record.local_loading = false
                  if (_result.code == 0) {
                    Messages.add(message.success('操作成功'))
                    tableData.data.source.splice(index, 1)
                  } else {
                    Messages.add(message.error(`操作失败[${_result.msg}]`))
                  }
                }}
              >
                <a-button type="primary" danger loading={record.local_loading}>
                  删除
                </a-button>
              </a-popconfirm>
            </a-space>
          )
        },
      },
    ]
    let route = useRoute()
    let router = useRouter()

    let _roles = reactive({
      key: 'roleId',
      initValue: null,
      source: [],
      uiType: 'select',
      col: { span: 6 },
      attr: {
        allowClear: true,
        placeholder: '角色名称',
      },
    })
    let form_config = [
      _roles,
      {
        key: 'btns',
        initValue: null,
        uiType: 'custom',
        col: {
          span: 6,
        },
        ui: (
          <a-space>
            <a-button
              loading={loading.search_loading}
              type="primary"
              onClick={() => {
                pagination.data.current = 1
                searchData()
              }}
              v-slots={{
                icon: () => {
                  return <SearchOutlined />
                },
              }}
            >
              搜索
            </a-button>
            <a-button
              loading={loading.search_loading}
              type="primary"
              danger
              onClick={() => {
                form_ref.value.resetState(cloneDeep(_bak_statue))
                pagination.data.current = 1
                searchData()
              }}
              v-slots={{
                icon: () => {
                  return <ClearOutlined />
                },
              }}
            >
              重置
            </a-button>
          </a-space>
        ),
      },
    ]

    authRoleList({ isMenu: 1, size: 1000000, index: 1, canBind: true }).then(
      (x) => {
        _roles.source = x.data.records.map((x) => {
          return { value: x.id, label: x.roleName }
        })
      }
    )

    let form_state = reactive({ data: MakeFormState(form_config) })

    let _bak_statue = cloneDeep(form_state.data)

    let searchData = async () => {
      fromStateToQuery({
        path: route.path,
      })
    }
    //分布配置
    let pagination = reactive({
      data: createPagination(searchData, true, false),
    })
    //切换分页
    // pagination.data.onChange = (pageNumber, pageSize) => {
    //   pagination.data.current = pageNumber
    //   pagination.data.pageSize = pageSize
    //   searchData()
    // }

    // let form_state = reactive({
    //   data: {
    //     userId: null,
    //     roleId: null,
    //   },
    // });
    let loading = reactive({ search_loading: false })

    let { fromStateToQuery } = useUrl({
      fn: async () => {
        loading.search_loading = true
        let _params = {
          size: pagination.data.pageSize,
          index: pagination.data.current,
          ...form_state.data,
        }
        let _result = await authUserRoleList(_params)
        loading.search_loading = false
        if (_result.code != 0) {
          Messages.add(message.error(`获取数据发生错误[${_result.msg}]`))
          return
        }
        tableData.data.source = _result.data?.records
        pagination.data.total = _result.data?.total
        pagination.data.current = _result.data?.index
        pagination.data.pageSize = _result.data?.size
      },
      formState: [{ key: 'roleId', fn: transform_pre_fn['fn.number'] }],
    })

    let [roleForm] = useWin({
      component: (
        <BindUser
          onAdd={async ({ params, innerCallBack }) => {
            let _result = await authUserRoleAdd(params)
            if (_result.code == 0) {
              Messages.add(message.success('操作成功'))
              _result.data.map((x) => {
                tableData.data.source.push(x)
              })
            } else {
              Messages.add(message.error(`操作失败[${_result.msg}]`))
            }
            innerCallBack(_result)
          }}
        />
      ),
      attr: {
        title: '绑定帐号',
      },
    })

    let createRoleHandler = () => {
      roleForm({
        params: {},
      })
    }
    let form_ref = ref()
    return {
      tableData,
      pagination,
      loading,
      custom,
      createRoleHandler,
      form_config,
      form_state,
      form_ref,
      searchData,
    }
  },
  render() {
    return (
      <>
        <a-row>
          <a-col span={24}>
            <MakeForm
              ref="form_ref"
              formConfig={this.form_config}
              value={this.form_state.data}
              class="colorBlock_child search_form"
              enterCallBack={() => {
                this.pagination.data.current = 1
                this.searchData()
              }}
            />
          </a-col>
          <a-col span={24}>
            <DataTable
              data={this.tableData}
              uiAttr={{
                scroll: { x: null },
                tableLayout: 'fixed',
                bordered: true,
              }}
              custom={this.custom}
              loading={this.loading}
            >
              <a-space>
                <a-button type="primary" onClick={this.createRoleHandler}>
                  绑定成员
                </a-button>
              </a-space>
            </DataTable>
          </a-col>
        </a-row>

        <a-affix {...this.pagination_affix_attr()}>
          <div class="affix">
            <a-pagination {...this.pagination.data} />
          </div>
        </a-affix>
      </>
    )
  },
})
</script>
